const secret = 'some'
const jwt = require("jsonwebtoken")
const release = require('../routes/release')
const { open, receive } = global.config.auth

if (open) {
  release.post(receive, async (ctx, next) => {
    ctx.app.context.ruleMap = ctx.request.body
    ctx.stop('SUCCESS')
  })
}
module.exports = app => {
  // 挂载获取token的方法
  app.context.getToken = function (obj) {
    return jwt.sign({ ...obj, exp: Date.now() + 1000 * 60 * 60 }, secret)
  }
  // 挂载放行的路由（登录注册等）
  app.use(release.routes(), release.allowedMethods())
  // 检测token中间件
  app.use(async (ctx, next) => {
    const { token } = ctx.header
    if (token) {
      let info
      try {
        info = jwt.verify(token, secret);
      } catch (error) {
        ctx.stop('AUTH_ERROE')
      }
      if (info.exp < Date.now()) {
        ctx.stop('LOGIN_TIMEOUT')
      } else {
        ctx.tokenInfo = info
        await next()
      }
    } else {
      ctx.stop('AUTH_ERROE')
    }
  });
}
